<template>
  <a-modal
    class="atlas-page"
    :visible="visible"
    :maskClosable="false"
    :width="width"
    :title="title"
    :okText="okText"
    :cancelText="cancelText"
    :footer="null"
    :maskStyle="{ background: 'rgba(153,153,153,0.40)' }"
    :afterClose="handleAfterClose"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-transfer
      v-if="visible"
      v-model:target-keys="targetKeys"
      :data-source="state.articleList"
      :show-select-all="false"
      :titles="['文章库', `已收录${targetKeys.length}篇文章`]"
      :rowKey="(record:any) => record.article_id"
      @change="onChange"
    >
      <template #children="{ direction, filteredItems, selectedKeys, onItemSelectAll, onItemSelect }">
        <div v-if="direction === 'left'" class="left-filter">
          <a-cascader
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
            class="w-[200px] margin-8"
            change-on-select
            :allowClear="false"
            :field-names="{ label: 'name', value: 'id', children: 'subcateg' }"
            :options="state.articleClassList"
            placeholder="全部分类"
            @change="handleSelectChange"
          >
            <template #suffixIcon>
              <a-tooltip placement="top" color="#fff">
                <template #title> 双击选中父级 </template>
                <div class="ellipsis-text"><question-circle-outlined /></div>
              </a-tooltip>
            </template>
          </a-cascader>
          <a-input
            v-model:value="leftState.article_id"
            allowClear
            :maxlength="19"
            :onkeyup="
              () => {
                if (leftState.article_id) leftState.article_id = leftState.article_id.replace(/\D/g, '')
              }
            "
            :onafterpaste="
              () => {
                if (leftState.article_id) leftState.article_id = leftState.article_id.replace(/\D/g, '')
              }
            "
            placeholder="文章ID"
            class="w-[150px] text-[rgba(0, 0, 0, 0.25)] mr-[8px]"
          />
          <a-input
            v-model:value="leftState.article_keyword"
            allowClear
            placeholder="文章名称关键词"
            class="w-[166px] text-[rgba(0, 0, 0, 0.25)] mr-[8px]"
          />
          <a-button type="primary" @click="leftSearch">搜索</a-button>
        </div>

        <a-table
          v-if="direction === 'left'"
          id="leftArticleTable"
          :row-selection="
            getRowSelection({
              selectedKeys,
              onItemSelectAll,
              onItemSelect
            })
          "
          row-key="article_id"
          :pagination="false"
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :data-source="filteredItems"
          size="small"
          :loading="state.loading"
          :custom-row="(item: any) => ({
            onClick: () => {
              onItemSelect(item.key, !selectedKeys.includes(item.key), item);
            },
          })
          "
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'sort'">
              <menu-outlined />
            </template>
            <template v-if="column.key === 'article_name'">
              <a-tooltip placement="top" color="#fff" v-if="record && record.article_name.length > 0">
                <template #title>
                  {{ record.article_name }}
                </template>
                <div class="ellipsis-text">
                  {{ record.article_name }}
                </div>
              </a-tooltip>
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'article_price_type'">
              {{ getArticleType(record) }}
            </template>
            <template v-if="column.key === 'article_popularity'">
              {{ formatNumber(record.article_popularity) }}
            </template>
          </template>
        </a-table>
        <a-pagination
          v-if="direction === 'left'"
          show-size-changer
          :defaultPageSize="10"
          :pageSizeOptions="['10', '20', '50', '100']"
          class="flex justify-end mt-[8px]"
          :show-total="(total:number)=>`共${total}条`"
          :total="queryState.total"
          @change="handlePaginationChange"
        />
        <!--
         <div v-if="direction === 'right'" class="left-filter">
          <a-input
            v-model:value="rightState.atlasId"
            placeholder="请输入图集ID"
            class="w-[150px] text-[rgba(0, 0, 0, 0.25)] my-[8px]"
          />
          <a-input
            v-model:value="rightState.keyword"
            placeholder="请输入图集名称关键词"
            class="w-[166px] text-[rgba(0, 0, 0, 0.25)] mr-[8px]"
          />
          <a-button type="primary" @click="rightSearch" >搜索</a-button>
        </div>
        -->
        <a-table
          v-if="direction === 'right'"
          :pagination="false"
          id="rightAtlasTable"
          :row-selection="
            getRowSelection({
              selectedKeys,
              onItemSelectAll,
              onItemSelect
            })
          "
          row-key="article_id"
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :data-source="filteredItems"
          size="small"
          :custom-row="(item: any) => ({
            onClick: () => {
              onItemSelect(item.key, !selectedKeys.includes(item.key), item);
            },
          })
          "
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'article_name'">
              <a-tooltip placement="top" color="#fff" v-if="record && record.article_name.length > 0">
                <template #title>
                  {{ record.article_name }}
                </template>
                <div class="ellipsis-text">
                  {{ record.article_name }}
                </div>
              </a-tooltip>
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'article_price_type'">
              {{ getArticleType(record) }}
            </template>
            <template v-if="column.key === 'article_popularity'">
              {{ formatNumber(record.article_popularity) }}
            </template>
          </template>
        </a-table>
      </template>
    </a-transfer>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { leftColumn, rightColumn, videoData, PRICE_TYPE } from '../dataSource'
import type { ArticleListData, IAlbum } from '@/types/site/article/articleList'
import { leftState, resetDialogState } from '../state'
//import Sortable from 'sortablejs'
import { message } from 'ant-design-vue'

import apis from '@/apis'
import { storage } from '@/utils/storage'
import { formatNumber } from '@/utils/format'
const {
  site: {
    article_list,
    article_classify_list,
    article_add_album_article,
    article_get_album_article,
    article_del_album_article
  }
} = apis

interface IState {
  visible: boolean
  width: number
  okText: string
  cancelText: string
  title: string
  albumId: string
}
const props = withDefaults(defineProps<IState>(), {
  visible: false,
  albumId: ''
})
const emit = defineEmits(['confirm', 'cancel'])
const state = reactive<{ loading: boolean; articleList: ArticleListData[]; articleClassList: any }>({
  loading: false,
  articleList: [] as ArticleListData[], //图集列表
  articleClassList: [] //筛选分类下拉数据
})
// const originTargetKeys = videoData.map(item => item.id);
const targetKeys = ref<string[]>([]) //targetsKeys指定的数据放右边
const leftColumns = ref(leftColumn)
const rightColumns = ref(rightColumn)
const siteId = storage.get('siteId')

const rightState = reactive({
  atlasId: undefined,
  keyword: undefined
})
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
//穿梭框change事件
const onChange = (nextTargetKeys: string[], direction: string, moveKeys: string[]) => {
  console.log('nextTargetKeys, direction, moveKeys: ', nextTargetKeys, direction, moveKeys)
  if (direction === 'right') {
    articleAddAlbumPic(moveKeys)
  } else {
    articleDelAlbumPic(moveKeys)
  }
}
//分类change事件
const handleSelectChange = (value: any, selectedOptions: any) => {
  console.log('value: ', value, selectedOptions)
  leftState.categ_id = value.length > 0 && value[0] ? value[0] : undefined
  leftState.subcateg_id = value.length > 0 && value[1] ? value[1] : undefined
}
//文章专辑添加文章
const articleAddAlbumPic = (keys: string[]) => {
  article_add_album_article({ album_id: props.albumId, article_id: keys }).then(() => {
    message.success('添加专辑文章成功')
    emit('confirm', false)
  })
}
//文章专辑删除文章
const articleDelAlbumPic = (keys: string[]) => {
  article_del_album_article({ album_id: props.albumId, article_id: keys }).then(() => {
    message.success('删除专辑文章成功')
    emit('confirm', false)
  })
}
//文章专辑获取文章
const getArticleAlbum = () => {
  article_get_album_article({ album_id: props.albumId }).then((res: any) => {
    console.log('res: ', res)
    targetKeys.value = res.articles.map((item: ArticleListData) => {
      return item.article_id
    })
    console.log('targetKeys.value: ', targetKeys.value)
  })
}
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getArticleList()
}
const getArticleList = () => {
  state.loading = true
  console.log('getActiveList')
  // 更新列表接口
  const params = {
    ...leftState,
    ...queryState
  }
  if (!params.article_id) params.article_id = undefined
  params.site_id = siteId
  params.status = 1
  article_list(params)
    .then((res: any) => {
      console.log('图集列表: ', res)
      state.articleList = res?.articles ?? []
      queryState.total = +res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.articles ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getArticleList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
//获取分类接口
const getArticleClass = () => {
  article_classify_list({ site_id: siteId, categ_status: 1 }).then((res: any) => {
    if (res?.categ.length === 0) return []
    res?.categ.unshift({ id: undefined, name: '全部分类' })
    state.articleClassList = res?.categ.map((item: any) => {
      for (var key in item) {
        if (Array.isArray(item[key]) && item[key].length === 0) {
          delete item[key]
        }
      }
      return item
    })
    console.log('state.articleClassList: ', state.articleClassList)
  })
}

const getRowSelection = ({
  selectedKeys, //哪些值应该被选中
  onItemSelectAll, //勾选一组条目
  onItemSelect //勾选条目
}: Record<string, any>) => {
  return {
    onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
      const treeSelectedKeys = selectedRows.map(({ key }) => key)
      onItemSelectAll(treeSelectedKeys, selected)
    },
    onSelect({ key }: Record<string, string>, selected: boolean, item: any) {
      console.log('key: ', key)
      console.log('item: ', item)
      onItemSelect(key, selected, item)
    },
    selectedRowKeys: selectedKeys
  }
}
const leftSearch = () => {
  console.log(leftState, 'leftState')
  getArticleList()
}
const rightSearch = () => {
  console.log(rightState, 'rightState')
}
//重置筛选项
const handleAfterClose = () => {
  resetDialogState()
}
const handleOk = () => {
  emit('confirm', false)
}
const handleCancel = () => {
  emit('cancel')
}
//获取收费状态
const getArticleType = computed(() => (item: any) => {
  if (item.article_price_type === 1) {
    return '免费'
  } else {
    return PRICE_TYPE[item.article_price_type] + '-' + item.article_price + '金币'
  }
})
//防抖
const antiShake = (time: number) => {
  return setTimeout(() => {
    console.log(`防抖`)
    getArticleList()
  }, time)
}
let timer: any = null
watch(
  [() => leftState.categ_id, () => leftState.subcateg_id, () => leftState.article_id, () => leftState.article_keyword],
  (value) => {
    console.log('value: ', value)
    if (value) {
      console.log('value: ', value)
      clearTimeout(timer)
      timer = antiShake(500)
    }
  }
)
watch(
  () => props.visible,
  (val) => {
    // if (visible.value) return initSortable()
    if (!val) return false
    getArticleClass()
    getArticleList()
    getArticleAlbum()
    console.log(props.albumId, 'props.albumId')
  },
  {
    deep: true
  }
)
</script>
<style lang="less">
.ellipsis-text {
  max-width: 100px !important;
  white-space: nowrap;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
.ant-transfer-list-body {
  position: relative;
}
.ant-table-wrapper {
  min-height: 114px;
}
.atlas-page {
  .left-filter {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
    font-size: 14px;

    .margin-8 {
      margin: 0 8px;
    }
  }
}

.ant-modal-body {
  padding: 32px 40px;
  box-sizing: border-box;
}
.ant-transfer-list {
  width: 49% !important;
}
.ant-transfer-list-body {
  padding: 16px;
}

.ant-transfer-list-header-selected {
  span:nth-of-type(1) {
    display: none;
  }
}

.ant-modal-header {
  background: rgba(0, 0, 0, 0.04) !important;
  border: none !important;

  .ant-modal-title {
    color: #262626;
  }
}

.ant-modal-footer {
  border: none;
  border-radius: 0 0 2px 2px;
  padding: 0 40px 24px;

  .ant-btn-primary {
    margin-left: 16px !important;
  }
}

.ant-modal-content {
  border-radius: 6px;

  .ant-modal-close {
    color: #000 !important;
  }
}
</style>
